package me.khrystal.activities;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import me.khrystal.MainApplication;
import me.khrystal.gitbranch.R;
import me.khrystal.model.CheckPatchResponse;
import me.khrystal.net.NetworkConstants;
import me.khrystal.net.RequestServerTask;
import me.khrystal.util.HttpUtil;
import me.khrystal.util.Settings;

public class SplashActivity extends AppCompatActivity implements Runnable{

    public int osVersion;
    public int patchVersion;
    public static final String TAG = "CheckPatch";
    private static final String APATCH_PATH = "/out.apatch";
    public static final String APATCH_DIR = "/AndFixDemo";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        Thread thread = new Thread(this);
        thread.start();
    }


    @Override
    public void run() {
        try {
            Thread.sleep(1400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            osVersion = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        patchVersion = Settings.getPatchVersion();

        //TODO do request check patch
        new RequestServerTask<CheckPatchResponse>(CheckPatchResponse.class,this){

            @Override
            protected String requestServer() {
                Map<String ,Object> params = new HashMap<>();
                params.put("osversion",osVersion);
                params.put("patch", patchVersion);
                return HttpUtil.get(NetworkConstants.CHECK_VERSION,params);
            }

            @Override
            protected void onSuccess(final CheckPatchResponse result) {
                if (result!=null){
                    if (osVersion>result.data.osversion){
                        //TODO remove patch
                        MainApplication.getInstance().mPatchManager.removeAllPatch();
                        Settings.setPatchVersion(0);
                        mHandler.sendEmptyMessage(23);
                    }else{

                        if (patchVersion<result.data.patch){
                            //TODO add patch
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
                                    if (sdCardExist){
                                        String patchFileDirString = Environment.getExternalStorageDirectory()
                                                .getAbsolutePath() + APATCH_DIR;
                                        File f = new File(patchFileDirString);
                                        if (!f.exists()){
                                            f.mkdir();
                                        }
                                        HttpUtil.downloadFile(result.data.url,patchFileDirString+APATCH_PATH);
                                        try {
                                            MainApplication.getInstance().mPatchManager.addPatch(patchFileDirString+APATCH_PATH);
                                            Settings.setPatchVersion(result.data.patch);
                                            mHandler.sendEmptyMessage(21);
                                        } catch (IOException e) {
                                            mHandler.sendEmptyMessage(22);
                                        }
                                    }else {
                                        mHandler.sendEmptyMessage(20);
                                    }
                                }
                            }).start();
                        }else {
                            boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
                            if (sdCardExist){
                                final String patchFileDirString = Environment.getExternalStorageDirectory()
                                        .getAbsolutePath() + APATCH_DIR;
                                File f = new File(patchFileDirString);
                                if (!f.exists()){
                                    f.mkdir();
                                }
                                f = new File(patchFileDirString+APATCH_PATH);
                                if (f.exists()) {
                                    try {
                                        MainApplication.getInstance().mPatchManager.addPatch(patchFileDirString + APATCH_PATH);
                                        Settings.setPatchVersion(result.data.patch);
                                        mHandler.sendEmptyMessage(21);
                                    } catch (IOException e) {
                                        mHandler.sendEmptyMessage(22);
                                    }
                                }else {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            HttpUtil.downloadFile(result.data.url,patchFileDirString+APATCH_PATH);
                                            try {
                                                MainApplication.getInstance().mPatchManager.addPatch(patchFileDirString + APATCH_PATH);
                                                Settings.setPatchVersion(result.data.patch);
                                                mHandler.sendEmptyMessage(21);
                                            } catch (IOException e) {
                                                mHandler.sendEmptyMessage(22);
                                            }
                                        }
                                    }).start();
                                }
                            }else {
                                mHandler.sendEmptyMessage(20);
                            }
                        }
                    }
                } else {
                    mHandler.sendEmptyMessage(20);
                }
            }
        }.start();
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 20:
                    Toast.makeText(SplashActivity.this,"nothing",Toast.LENGTH_LONG).show();
                    break;
                case 21:
                    Toast.makeText(SplashActivity.this,"add patch",Toast.LENGTH_LONG).show();
                    break;
                case 22:
                    Toast.makeText(SplashActivity.this,"add patch error",Toast.LENGTH_LONG).show();
                    break;
                case 23:
                    Toast.makeText(SplashActivity.this,"remove patch",Toast.LENGTH_LONG).show();
                    break;
            }

            Intent intent = new Intent(SplashActivity.this,MainActivity.class);
            SplashActivity.this.startActivity(intent);
            finish();
        }
    };

}
